package com.song.server.controller;

import com.song.server.dto.LoginParam;
import com.song.server.entity.Admin;
import com.song.server.service.AdminService;
import com.song.server.vo.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@RestController
public class LoginController {

    @Autowired
    private AdminService adminService;

    /**
     * 登录之后返回token
     */
    @PostMapping("/login")
    public RespBean login(@RequestBody LoginParam param, HttpServletRequest request) {
        return adminService.login(param.getUsername(), param.getPassword(), param.getCode(), request);
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/admin/info")
    public Admin getAdminInfo(Principal principal) {
        if (null == principal) {
            return null;
        }
        String username = principal.getName();
        Admin admin = adminService.getAdminByName(username);
        // 用户密码置空
        admin.setPassword(null);
        // 设置用户拥有的角色列表
        admin.setRoles(adminService.getRoles(admin.getId()));
        return admin;
    }

    /**
     * 注销登录
     */
    @PostMapping("/logout")
    public RespBean logout() {
        return RespBean.success("注销成功！");
    }

}
